// 获取元素
let tbody = document.querySelector('tbody')
let btnopn = document.querySelector('.btnopn') //打开模态框按钮
let addModalLabel = document.querySelector('#addModalLabel') //模态框标题
let btnadd = document.querySelector('.btnadd')  //确认按钮

// 属性
let nameEle = document.querySelector('[name="name"]')
let ageEle = document.querySelector('[name="age"]')
let groupEle = document.querySelector('[name="group"]')
let sexEles = document.querySelectorAll('[name="sex"]')
let phoneEle = document.querySelector('[name="phone"]')
let salaryEle = document.querySelector('[name="salary"]')
let truesalaryEle = document.querySelector('[name="truesalary"]')
let provinceEle = document.querySelector('[name="province"]')
let cityEle = document.querySelector('[name="city"]')
let countyEle = document.querySelector('[name="county"]')
// ===========================渲染============================
function init() {
    // 发请求
    axios({
        url: '/student/list'
    }).then(function (res) {
        let htmlStr = ''
        res.data.data.forEach(function (value, index) {
            htmlStr += `<tr>
                            <th scope="row">${value.id}</th>
                            <td>${value.name}</td>
                            <td>${value.age}</td>
                            <td>${value.sex}</td>
                            <td>${value.group}</td>
                            <td>${value.phone}</td>
                            <td>${value.salary}</td>
                            <td>${value.truesalary}</td>
                            <td>${value.province + value.city + value.county}</td>
                            <td>
                            <button type="button" class="btn btn-primary btn-sm btndit" data-id="${value.id}">修改</button>
                            <button type="button" class="btn btn-danger btn-sm btndel" data-id="${value.id}" >删除</button>
                            </td>
                        </tr>`
        })
        tbody.innerHTML = htmlStr
    })
}
// 调用函数渲染页面
init()

// ===========================新增============================
// 打开模态框
btnopn.addEventListener('click', function () {
    $('#addModal').modal('show')
    addModalLabel.innerHTML = '录入新学员'
    btnadd.innerHTML = '确认添加'
})
// 省市县级联
// 省
axios({
    url: '/geo/province'
}).then(function (res) {

    let htmlStr = '<option selected value="">--省--</option>'
    res.data.forEach(function (value, index) {
        htmlStr += `'<option  value="${value}">${value}</option>'`
    })
    provinceEle.innerHTML = htmlStr
})
// 市
provinceEle.addEventListener('change', function () {
    // 重置市和县
    cityEle.innerHTML = `<option selected value="">--市--</option>`
    countyEle.innerHTML = `<option selected value="">--县--</option>`

    let pname = provinceEle.value
    // 判断没有值不发请求
    if (!provinceEle.value) {
        return
    }
    axios({
        url: '/geo/city',
        params: { pname }
    }).then(function (res) {
        let htmlStr = '<option selected value="">--市--</option>'
        res.data.forEach(function (value, index) {
            htmlStr += `'<option  value="${value}">${value}</option>'`
        })
        cityEle.innerHTML = htmlStr
    })
})
// 县
cityEle.addEventListener('change', function () {
    // 重置县
    countyEle.innerHTML = `<option selected value="">--县--</option>`

    let pname = provinceEle.value
    let cname = cityEle.value
    if (!cityEle.value) {
        return
    }
    axios({
        url: '/geo/county',
        params: { pname, cname }
    }).then(function (res) {
        let htmlStr = '<option selected value="">--县--</option>'
        res.data.forEach(function (value, index) {
            htmlStr += `'<option  value="${value}">${value}</option>'`
        })
        countyEle.innerHTML = htmlStr
    })
})

// 表单验证
function student() {
    return {
        fields: {
            name: {
                validators: {
                    notEmpty: {
                        message: '姓名不能为空',
                    },
                    stringLength: {
                        min: 2,
                        max: 10,
                        message: '姓名长度2~10位'
                    }
                }
            },
            age: {
                validators: {
                    notEmpty: {
                        message: '年龄不能为空',
                    },
                    greaterThan: {
                        value: 18,
                        message: '年龄不能小于18岁'
                    },
                    lessThan: {
                        value: 60,
                        message: '年龄不能超过60岁'
                    }
                }
            },
            sex: {
                validators: {
                    choice: {
                        min: 1,
                        max: 1,
                        message: '请选择性别'
                    }
                }
            },
            group: {
                validators: {
                    notEmpty: {
                        message: '组号不能为空',
                    },
                    regexp: {
                        regexp: /^\d{1,2}$/,
                        message: '请选择有效的组号'
                    }
                }
            },
            phone: {
                validators: {
                    notEmpty: {
                        message: '手机号不能为空',
                    },
                    regexp: {
                        regexp: /^1\d{10}$/,
                        message: '请填写有效的手机号'
                    }
                }
            },
            salary: {
                validators: {
                    notEmpty: {
                        message: '实际薪资不能为空',
                    },
                    greaterThan: {
                        value: 800,
                        message: '期望薪资不能低于800'
                    },
                    lessThan: {
                        value: 100000,
                        message: '期望薪资不能高于100000'
                    }
                }
            },
            truesalary: {
                validators: {
                    notEmpty: {
                        message: '实际薪资不能为空',
                    },
                    greaterThan: {
                        value: 800,
                        message: '实际薪资不能低于800'
                    },
                    lessThan: {
                        value: 100000,
                        message: '实际薪资不能高于100000'
                    }
                }
            },
            province: {
                validators: {
                    notEmpty: {
                        message: '省份必填',
                    },
                }
            },
            city: {
                validators: {
                    notEmpty: {
                        message: '市必填',
                    },
                }
            },
            county: {
                validators: {
                    notEmpty: {
                        message: '县必填',
                    },
                }
            },
        }
    }
}

let id
// jq框架完成表单新增提交新增或编辑
$('.add-form').bootstrapValidator(student()).on('success.form.bv', function (e) {
    e.preventDefault()
    // 生成一个formdata,this指向表单自己
    let formdata = new FormData(this)

    let data = {}
    // 遍历数据转化
    formdata.forEach(function (value, key) {
        data[key] = value
    })
    // 判断市县为空不发请求
    if (cityEle.value == '' || countyEle.value == '') {
        toastr.error('请正确选择市县');
        return
    }
    if (addModalLabel.innerHTML == '录入新学员') {
        // 发请求
        axios({
            url: "/student/add",
            method: 'post',
            data
        }).then(function (res) {
            toastr.success('添加学员信息成功')
            $('#addModal').modal('hide')
            // 调用函数渲染页面
            init()
        })
    } else {
        data.id = id
        // 发请求
        axios({
            url: '/student/update',
            method: 'put',
            data
        }).then(function (res) {
            toastr.success('编辑学员信息成功')
            $('#addModal').modal('hide')
            // 调用函数渲染页面
            init()
        })
    }
})

// ===========================删除============================
// 事件委托
tbody.addEventListener('click', function (e) {
    if (e.target.classList.contains('btndel')) {
        let id = e.target.dataset.id
        axios({
            url: '/student/delete',
            method: 'delete',
            params: { id }
        }).then(function (res) {
            toastr.success('删除学员信息成功')
            // 调用函数渲染页面
            init()
        })
    }
})

// ===========================编辑============================
// 打开模态框
tbody.addEventListener('click', function (e) {
    if (e.target.classList.contains('btndit')) {
        $('#addModal').modal('show')
        addModalLabel.innerHTML = '编辑学员'
        btnadd.innerHTML = '确认编辑'
        id = e.target.dataset.id
        // 发请求
        axios({
            url: '/student/one',
            method: 'get',
            params: { id }
        }).then(function (res) {
            let data = res.data.data

            nameEle.value = data.name
            ageEle.value = data.age
            phoneEle.value = data.phone
            salaryEle.value = data.salary
            truesalaryEle.value = data.truesalary
            groupEle.value = data.group

            data.sex == "男" ? sexEles[0].checked = true : sexEles[1].checked = true

            provinceEle.value = data.province
            cityEle.innerHTML = `<option value="">${data.city}</option>`
            countyEle.innerHTML = `<option value="">${data.county}</option>`

            // 自定义触发事件
            let event = new Event('change');
            provinceEle.dispatchEvent(event);
            setTimeout(() => {
                cityEle.value = data.city

                let event = new Event('change');
                cityEle.dispatchEvent(event);

                setTimeout(() => {
                    countyEle.value = data.county
                }, 500);
            }, 500);
        })

    }
})